var mediaSource = new MediaSource();
mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
var mediaRecorder;
var recordedBlobs;
var sourceBuffer;
var littleVideo = false;

var gumVideo = document.querySelector('video#gum');
var showVideo = document.querySelector('video#showVideo');
var showCanvasControl ;


var recordButton = document.querySelector('button#record');
var playButton = document.querySelector('button#play');


var downloadButton = document.querySelector('button#download');
var reStartButton = document.querySelector('button#reStart');
var uploadBtn = document.querySelector('button#upload');

recordButton.onclick = toggleRecording;
playButton.onclick = play;
//downloadButton.onclick = download;
//reStartButton.onclick = restartRecord;
//uploadBtn.onclick = upload;

// window.isSecureContext could be used for Chrome
/*var isSecureOrigin = location.protocol === 'https:' ||
    location.hostname === 'localhost';
if (!isSecureOrigin) {
    alert('getUserMedia() must be run from a secure origin: HTTPS or localhost.' +
        '\n\nChanging protocol to HTTPS');
    location.protocol = 'HTTPS';
}*/

var constraints = {
    audio: true,
    video: true
};


function drawBigVideo(videoObj,c){
    var ctx=c.getContext('2d');
    //清除画布内容，重新画满
    ctx.clearRect(0,0,c.width,c.height);
    ctx.drawImage(videoObj,0,0,c.width,c.height);
}

function handleSuccess(stream) {
    recordButton.disabled = false;
    console.log('getUserMedia() got stream: ', stream);
    window.stream = stream;
    if (window.URL) {
        //gumVideo.src = window.URL.createObjectURL(stream);
        gumVideo.srcObject = stream;
    } else {
        gumVideo.src = stream;
    }

    var c=document.getElementById("myCanvas");

    gumVideo.addEventListener('play',function() {
        showCanvasControl=window.setInterval(function() {
            console.log("111");
            drawBigVideo(gumVideo,c);
        },20);
    },false);

    var i;
    showVideo.addEventListener('play',function() {
        i=window.setInterval(function() {
            console.log("222");
            drawBigVideo(showVideo,c);
        },20);
    },false);
    showVideo.addEventListener('pause',function() {if(i){window.clearInterval(i);}},false);
    showVideo.addEventListener('ended',function() {if(i){clearInterval(i);console.log("stop......");}},false);
}


function handleError(error) {
    console.log('navigator.getUserMedia error: ', error);
}

navigator.mediaDevices.getUserMedia(constraints).
then(handleSuccess).catch(handleError);

function handleSourceOpen(event) {
    console.log('MediaSource opened');
    sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
    console.log('Source buffer: ', sourceBuffer);
}

function handleDataAvailable(event) {
    if (event.data && event.data.size > 0) {
        recordedBlobs.push(event.data);
    }
}

function handleStop(event) {
    gumVideo.pause();
    gumVideo.currentTime=0;
    window.clearInterval(showCanvasControl);
    console.log('Recorder stopped: ', event);
}

function toggleRecording() {
    if (recordButton.textContent === '录制' || recordButton.textContent === '重录') {
        if( recordButton.textContent === '重录') {
            console.log("重录。。。。。。。。。。。。。。。");
            gumVideo.play();
        }
        littleVideo = false;
        startRecording();
    } else {
        stopRecording();
        recordButton.textContent = '重录';
        playButton.disabled = false;
    }
}

function startRecording() {
    //todo：显示录制中 提示
    recordedBlobs = [];
    var options = {mimeType: 'video/webm;codecs=vp9'};
    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        console.log(options.mimeType + ' is not Supported');
        options = {mimeType: 'video/webm;codecs=vp8'};
        if (!MediaRecorder.isTypeSupported(options.mimeType)) {
            console.log(options.mimeType + ' is not Supported');
            options = {mimeType: 'video/webm'};
            if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                console.log(options.mimeType + ' is not Supported');
                options = {mimeType: ''};
            }
        }
    }
    try {
        mediaRecorder = new MediaRecorder(window.stream, options);
    } catch (e) {
        console.error('Exception while creating MediaRecorder: ' + e);
        alert('Exception while creating MediaRecorder: '
            + e + '. mimeType: ' + options.mimeType);
        return;
    }
    console.log('Created MediaRecorder', mediaRecorder, 'with options', options);
    recordButton.textContent = '停止';
    playButton.disabled = true;
    mediaRecorder.onstop = handleStop;
    mediaRecorder.ondataavailable = handleDataAvailable;
    mediaRecorder.start(10); // collect 10ms of data
    console.log('MediaRecorder started', mediaRecorder);
}

function stopRecording() {
    //影藏录制中提
    mediaRecorder.stop();
    console.log('Recorded Blobs: ', recordedBlobs);
    //recordedVideo.controls = true;
}

function play() {
    var blob = new Blob(recordedBlobs, {type: 'video/mp4'});
    //recordedVideo.src = window.URL.createObjectURL(superBuffer);
    showVideo.src = window.URL.createObjectURL(blob);
}


function restartRecord(){
    //清楚存留 按钮功能重置
    recordButton.textContent = '录制';
    playButton.disabled = true;
    downloadButton.disabled = true;
    reStartButton.disabled = true;
    //handleSuccess();
    navigator.mediaDevices.getUserMedia(constraints).
    then(handleSuccess).catch(handleError);
}